package com.gxs.tga.poc.service;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.gxs.tga.poc.domain.TgaCompany;
import com.gxs.tga.poc.domain.exceptions.DuplicateTgaCompany;
import com.gxs.tga.poc.domain.exceptions.TgaCompanyNotFound;
import com.gxs.tga.poc.repository.TgaCompanyRepository;

@Service
public class TgaCompanyServiceImpl implements TgaCompanyService
{

	@Resource
	private TgaCompanyRepository tgaCompanyRepository;

	@Override
	@Transactional
	public TgaCompany create(TgaCompany test) throws DuplicateTgaCompany
	{
		TgaCompany existing = this.findById(test.getCompId());
		
		if(existing != null)
		{
			throw new DuplicateTgaCompany();
		}
		
		TgaCompany createdTgaCompany = test;
		return tgaCompanyRepository.save(createdTgaCompany);
	}

	@Override
	@Transactional
	public TgaCompany findById(String id)
	{
		return this.tgaCompanyRepository.findOne(id);
	}

	@Override
	@Transactional(rollbackFor = TgaCompanyNotFound.class)
	public TgaCompany delete(String id) throws TgaCompanyNotFound
	{
		TgaCompany deletedTgaCompany = tgaCompanyRepository.findOne(id);

		if (deletedTgaCompany == null)
			throw new TgaCompanyNotFound();

		tgaCompanyRepository.delete(deletedTgaCompany);
		return deletedTgaCompany;
	}

	@Override
	@Transactional
	public List<TgaCompany> findAll()
	{
		return tgaCompanyRepository.findAll();
	}

	@Override
	@Transactional(rollbackFor=TgaCompanyNotFound.class)
	public TgaCompany update(TgaCompany test) throws TgaCompanyNotFound {
		TgaCompany updatedTgaCompany = tgaCompanyRepository.findOne(test.getCompId());
		
		if (updatedTgaCompany == null)
			throw new TgaCompanyNotFound();

		updatedTgaCompany.setCompName(test.getCompName());
		updatedTgaCompany.setCountryName(test.getCountryName());
		updatedTgaCompany.setDunsNumber(test.getDunsNumber());
		updatedTgaCompany.setIndustryType(test.getIndustryType());
		updatedTgaCompany.setWebsiteUrl(test.getWebsiteUrl());
		
		return updatedTgaCompany;
	}
}
